/**
 * @license
 * Copyright 2021 KonghaYao 江夏尧 <dongzhongzhidong@qq.com>
 * SPDX-License-Identifier: Apache-2.0
 */
import createRouteMatcher from './createRouteMatcher.js';
import compose from 'koa-compose';
import { join } from 'path-browserify';
export default class Route {
    constructor(prefix, value, RouteMap, {}) {
        this.prefix = prefix;
        this.matcher = createRouteMatcher(prefix);

        this.RouteMap = RouteMap;
        this.initRoute(value);
    }
    allowedMethods = ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'];
    methodsMap = {};
    initRoute(callback) {
        const cbType = typeof callback;
        switch (cbType) {
            case 'string':
                // redirect
                break;
            case 'object':
                if (callback instanceof Array) {
                    this.initMethods(callback[0]);
                } else {
                    Object.entries(callback).forEach(([prefix, value]) => {
                        new Route(join(this.prefix, prefix), value, this.RouteMap, {});
                    });
                }
        }
    }
    initMethods(MethodMap) {
        // 只有有 method 的路由才能被匹配到
        this.RouteMap.add(this);
        // 如果 callback 是数组，
        Object.entries(MethodMap).forEach(([method, funcs]) => {
            this.methodsMap[method.toUpperCase()] = typeof funcs === 'function' ? funcs : compose(funcs);
        });
    }
    getMatched(method, path) {
        if (this.matcher(path) && this.allowedMethods.includes(method)) {
            return this.methodsMap[method];
        } else {
            return null;
        }
    }
}
